<template>
    <div>
        <mt-actionsheet :actions="actions" v-model="sheetVisible"></mt-actionsheet>
    </div>
</template>

<script>
import { getUploadToken } from "api/common";

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    compress: {
      type: Boolean,
      default: true
    },
    width: {
      type: [String, Number],
      default: "120"
    },
    height: {
      type: [String, Number],
      default: "120"
    },
    quality: {
      type: Number,
      default: 1
    },
    format: {
      type: String,
      default: "png"
    },
    save: {
      type: Boolean,
      default: false
    },
    base64: {
      type: Boolean,
      default: true
    },
    uploadTo: {
      type: String,
      default: ""
    },
    module: {
      type: String,
      default: "avatar"
    },
    loading: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      sheetVisible: this.value || false,
      actions: [
        {
          name: "拍照",
          method: this.takePhoto
        },
        {
          name: "从相册中选择",
          method: this.openAlbum
        }
      ]
    };
  },
  methods: {
    _resEmit(res) {
      if (this.uploadTo === "qiniu") {
        this.postToQiniu(res.path, (innerPath, key) => {
          this.$emit(
            "change",
            { path: this.base64 ? res.base64Path : res.path, key: key ,fullPath: innerPath },
            this.type
          );
        });
      } else {
        this.$emit("change", res.path, this.type);
      }
    },
    _isCompress(path) {
      if (this.compress) {
        this.compressImage(
          path,
          res => {
            this._resEmit(res);
          },
          false
        );
      } else {
        // 压缩才能转换成base64
        this._resEmit({ path: path });
      }
    },
    toBase64(path, callFun) {
      // andriod采用readAsDataURL转换成功，但是ios不兼容
      reader = new plus.io.FileReader();
      reader.onloadend = function(e) {
        callFun && callFun(e.target.result);
      };
      reader.readAsDataURL(path);
    },
    getBase64Code(path, callFun) {
      // 转换base64,兼容andrios和ios系统
      // path绝对路径

      var bitmap = new plus.nativeObj.Bitmap("test"); // test标识谁便取
      // 从本地加载Bitmap图片
      bitmap.load(
        path,
        () => {
          var base4 = bitmap.toBase64Data();
          callFun(base4);
          console.log("加载图片：" + base4);
        },
        e => {
          console.log("加载图片失败：" + JSON.stringify(e));
        }
      );
    },
    compressImage(path, callFun) {
      var _dstPath = path;
      var options = {
        src: path,
        dst: _dstPath,
        quality: this.quality,
        width: this.width,
        height: this.height,
        overwrite: true // 必须设置为true，否则andriod压缩会报错
      };

      if (this.format !== "") {
        _dstPath = path.substr(0, path.lastIndexOf(".") + 1) + this.format;
        options = Object.assign(options, {
          format: this.format,
          dst: _dstPath
        });
      }

      plus.zip.compressImage(
        options,
        entry => {
          if (entry.size / 1024 <= 512) {
            // 转化为base64
            if (this.base64) {
              this.getBase64Code(entry.target, res => {
                callFun && callFun({ path: entry.target, base64Path: res });
              });
            } else {
              callFun && callFun({ path: entry.target });
            }
          } else {
            Toast("图片需小于512KB");
          }
        },
        error => {
          console.log("Compress error：" + JSON.stringify(error));
        }
      );
    },
    getUploadOptions(callFun) {
      // 从服务器获取上传参数
      getUploadToken({
        module: this.module
      }).then(res => {
        console.log("获取返回参数:" + JSON.stringify(res));
        callFun && callFun(res);
      });
    },
    postToQiniu(file, callFun) {
      console.log("filename:" + file);
      /// <summary>上传指定路径的文件到七牛云空间</summary>
      this.getUploadOptions(options => {
        var uploader = plus.uploader.createUpload(
          options.domain,
          {
            method: "POST",
            timeout: 30,
            retry: 1,
            retryInterval: 10
          },
          (res, status) => {
            console.log("上传成功返回:" + JSON.stringify(res));
            if (this.loading) {
              Indicator.close();
            }
            if (status === 200) {
              var result = JSON.parse(res.responseText);
              callFun && callFun(options.downloadUrl, result.key);
              console.log(this.module + "key:" + result.key);
              // 调用服务端接口，将上传成功后的文件key提交到服务器
              console.info("文件 [{0}] 上传成功！".format(file));
            } else {
              console.error("文件 [{0}] 上传失败！\r\n error:".format(file));
            }
          }
        );
        uploader.addData("key", options.key);
        uploader.addData("token", options.token);
        uploader.addFile(file, {
          key: "file",
          name: "file"
        });
        console.log("开始上传文件：{0}！".format(file));
        uploader.start();
      });
    },
    _toLocalFileUrl(path) {
      if (this.loading) {
        Indicator.open();
      }
      if (this.type === "camera" && this.save) {
        plus.gallery.save(
          path,
          () => {},
          e => {
            console.log("保存失败: " + JSON.stringify(e));
          }
        );
      }
      plus.io.resolveLocalFileSystemURL(
        path,
        entry => {
          this._isCompress(entry.fullPath);
        },
        e => {
          console.log("读取录像文件错误：" + e.message);
        }
      );
    },
    takePhoto() {
      this.$emit("before-gallery");
      this.type = "camera";
      plus.camera.getCamera().captureImage(
        path => {
          this._toLocalFileUrl(path);
        },
        e => {},
        {
          filename: "_doc/gallery/",
          index: 1
        }
      );
    },
    openAlbum() {
      this.$emit("before-gallery");
      this.type = "pick";
      plus.gallery.pick(
        path => {
          this._toLocalFileUrl(path);
        },
        e => {
          this.$emit("cancel-gallery");
        },
        { filter: "image", multiple: false }
      );
    }
  },
  watch: {
    value(newVal) {
      this.sheetVisible = newVal;
    },
    sheetVisible(newVal) {
      this.$emit("input", newVal);
    }
  }
};
</script>

<style scoped>
</style>
